<template>
  <div style="padding: 10px">
    <!--    功能区域-->
    <div style="margin: 10px 0">
      <el-button type="primary" @click="add" v-if=isAdmin>新增</el-button>
    </div>

    <!--    搜索区域-->
    <div style="margin: 10px 0">
      <el-input v-model="search" placeholder="请输入关键字" style="width: 20%" clearable></el-input>
      <el-button type="primary" style="margin-left: 5px" @click="load">查询</el-button>
      <el-button type="primary" style="margin-left: 5px" @click="fullSearch">全文搜索</el-button>

    </div>
    <el-table
        v-loading="loading"
        :data="tableData"
        v-if="!searchShow"
        border
        stripe
        style="width: 100%">
      <el-table-column
          prop="title"
          label="标题"
          width="300">
      </el-table-column>
      <el-table-column
          prop="author"
          label="作者"
          width="140">
      </el-table-column>
      <el-table-column
          prop="category"
          label="分类"
          width="140">
      </el-table-column>
      <el-table-column
          v-if=isAdmin
          prop="status"
          label="状态"
          width="140">
        <template #default="scope">
<!--          <el-tag-->
<!--              :type="scope.row.status === 1 ? 'primary' : 'success'"-->
<!--              disable-transitions>{{ scope.row.status }}-->
<!--          </el-tag>-->
          <span v-if="scope.row.status===0"><el-tag type="primary">未发布</el-tag></span>
          <span v-if="scope.row.status===1"><el-tag type="success">已发布</el-tag></span>
<!--          <span v-if="scope.row.status<0">{{scope.row.status}}</span>-->
        </template>

      </el-table-column>
      <el-table-column
          prop="createTime"
          label="时间"
          width="180">
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="mini" @click="details(scope.row)">详情</el-button>
          <el-button size="mini" @click="handleEdit(scope.row)" v-if=isAdmin>编辑</el-button>
          <el-popconfirm title="确定删除吗？" @confirm="handleDelete(scope.row.id)" v-if=isAdmin>
            <template #reference>
              <el-button size="mini" type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-table
        :data="searchTableData"
        v-if="searchShow"
    >
      <el-table-column
          label=""
          width="800"
          border
      >
        <template #default="scope">
          <div style="width: 100%">
            <el-button type="text" size="medium" style="border:none;font-size: large" @click="details(scope.row)">
              <span v-html="scope.row.esTitle"></span>
            </el-button>

            <div style="margin-top: 5px;font-size: medium" v-html="scope.row.esContent"></div>

            <div style="margin-top: 5px">
              <span>{{ scope.row.author }}</span>
              <span style="margin-left: 10px">{{ scope.row.createTime }}</span>
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin: 10px 0;width: 800px" v-if="pageShow">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="form.title" v-model="dialogVisible" width="60%" fullscreen="true">
      <el-form :model="form" :inline="true">
        <el-form-item label="标题">
          <el-input v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="form.category"
                     placeholder="请选择">
            <el-option
                v-for="item in categoryOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="摘要" style="width: 800px">
          <el-input v-model="form.summary"></el-input>
        </el-form-item>

        <mavon-editor style="height: 100%;width: 100%;" ref=md @imgAdd="imgAdd"
                      @imgDel="imgDel" :scrollStyle="true" v-model="detail.mdContent"/>
        <!--        <div id="div1"></div>-->
        <!--        <el-form-item label="内容">-->
        <!--          <el-input v-model="form.price" style="width: 80%"></el-input>-->
        <!--        </el-form-item>-->
      </el-form>
      <template #footer>
          <span class="dialog-footer">
            <el-button @click="cancelHandler">取 消</el-button>
            <el-button type="info" @click="save(0)">保 存</el-button>
            <el-button type="primary" @click="save(1)">发 布</el-button>
          </span>
      </template>
    </el-dialog>

    <el-dialog :title="detail.title" v-model="vis" width="60%" fullscreen="true">
      <el-card>
        <div class="markdown-body" v-html="detail.htmlContent">
        </div>
        <link href="https://cdn.bootcss.com/github-markdown-css/2.10.0/github-markdown.min.css" rel="stylesheet">
        <link rel="stylesheet"
              href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/default.min.css">
      </el-card>
    </el-dialog>
  </div>
</template>

<script>

import request from "@/utils/request";
import 'mavon-editor/dist/css/index.css'

let editor;

export default {
  name: 'News',
  components: {},
  data() {
    return {
      loading: true,
      form: {},
      dialogVisible: false,
      search: '',
      currentPage: 1,
      pageSize: 10,
      total: 0,
      tableData: [],
      searchTableData: [],
      vis: false,
      searchShow: false,
      pageShow: true,
      detail: {},
      value: "123",
      noteStatus: 1,
      isAdmin: false,
      user: {},
      categoryOptions: [
          {value: "2", label: "后端"},
        {value: "3", label: "前端"},
        {value: "4", label: "人工智能"},
        {value: "5", label: "开发工具"},
        {value: "6", label: "程序人生"}
      ]
    }
  },
  created() {
    let userStr = sessionStorage.getItem("user") || "{}"
    this.user = JSON.parse(userStr)
    // 请求服务端，确认当前登录用户的 合法信息
    request.get("/v1/sys/user/" + this.user.sysUser.id).then(res => {
      if (res.code === '0') {
        this.user = res.data
        let roleCodeList = this.user.roles.map(r => r.code);
        while (roleCodeList.length > 0) {
          let roleCode = roleCodeList.pop();
          if (roleCode === 'super' || roleCode === 'admin') {
            this.isAdmin = true
            this.noteStatus = 0
            break
          }
        }
        this.load()
      }
    })
  },
  methods: {
    details(row) {
      this.detail = row
      this.vis = true
    },
    filesUploadSuccess(res) {
      console.log(res)
      this.form.cover = res.data
    },
    load() {
      this.searchShow = false;
      this.pageShow = true;

      console.log(this.searchShow)
      this.loading = true
      request.get("/note/list/" + this.noteStatus, {
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          title: this.search
        }
      }).then(res => {
        this.loading = false
        this.tableData = res.data.records
        this.total = res.data.total
      })
    },
    fullSearch() {
      this.searchShow = true;
      this.pageShow = false;
      if (this.search === '' || this.search === null) {
        this.search = 'spring'
      }
      request.get("/es/note/getByContent/", {
        params: {
          // pageNum: this.currentPage,
          // pageSize: this.pageSize,
          content: this.search
        }
      }).then(res => {
        console.log(res)
        this.searchTableData = res.data
      })
    },
    getStrategyOptions() {
      request.get("/note/update", this.form).then(res => {

      })
    },
    add() {
      this.dialogVisible = true
      this.form = {}
      this.detail = {}

      // this.$nextTick(() => {
      //   // 关联弹窗里面的div，new一个 editor对象
      //   if (!editor) {
      //     editor = new E('#div1')
      //
      //     // 配置 server 接口地址
      //     editor.config.uploadImgServer = 'http://' + window.server.filesUploadUrl + ':9090/files/editor/upload'
      //     editor.config.uploadFileName = "file"  // 设置上传参数名称
      //     editor.create()
      //   }
      //
      //   editor.txt.html("")
      //
      // })
    },
    cancelHandler() {
      this.dialogVisible = false
      this.detail = {}
    },
    save(status) {
      // this.form.content = editor.txt.html()  // 获取 编辑器里面的值，然后赋予到实体当中
      let htmlContext = this.$refs.md.d_render;
      let userStr = sessionStorage.getItem("user") || "{}"
      let user = JSON.parse(userStr)
      let noteStatus = this.form.status;
      this.form.author = user.sysUser.username
      this.form.htmlContent = htmlContext;
      this.form.mdContent = this.detail.mdContent;
      // console.log('cc'+this.form.category)
      // this.form.category = "默认"

      function noteUpdate() {
        this.form.status = status
        request.post("/note/update", this.form).then(res => {
          if (res.code === '0') {
            this.$message({
              type: "success",
              message: "更新成功"
            })
            this.load() // 刷新表格的数据
            this.dialogVisible = false  // 关闭弹窗
          } else {
            this.$message({
              type: "error",
              message: res.msg
            })
          }
        })
      }

      if (this.form.id) {  // 更新
        console.log(noteStatus)
        if (noteStatus === 1 && status === 0) {
          this.$confirm('该文章已发布，保存后将取消发布！\n如想保留发布状态，请点击发布按钮，是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            noteUpdate.call(this);
          }).catch(() => {
            // this.$message({
            //   type: 'info',
            //   message: '已取消删除'
            // });
          });
        } else {
          noteUpdate.call(this);
        }
      } else {  // 新增
        this.form.status = status
        request.post("/note/add", this.form).then(res => {
          if (res.code === '0') {
            this.$message({
              type: "success",
              message: "新增成功"
            })
            this.load() // 刷新表格的数据
            this.dialogVisible = false  // 关闭弹窗
          } else {
            this.$message({
              type: "error",
              message: res.msg
            })
          }
        })
      }

    },
    handleEdit(row) {
      this.form = JSON.parse(JSON.stringify(row))
      this.dialogVisible = true

      this.detail = row
    },
    handleDelete(id) {
      console.log(id)
      request.post("/note/del/" + id).then(res => {
        if (res.code === '0') {
          this.$message({
            type: "success",
            message: "删除成功"
          })
        } else {
          this.$message({
            type: "error",
            message: res.msg
          })
        }
        this.load()  // 删除之后重新加载表格的数据
      })
    },
    handleSizeChange(pageSize) {   // 改变当前每页的个数触发
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum) {  // 改变当前页码触发
      this.currentPage = pageNum
      this.load()
    },
    filterTag(value, row) {
      return row.status === value;
    },
  }
}
</script>


<style>

</style>
